package com.swt.testdemo.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.swt.testdemo.config.ResponseBean;
import com.swt.testdemo.config.ResponseMessage;
import com.swt.testdemo.dao.SysUserDao;
import com.swt.testdemo.entity.SysRoleEntity;
import com.swt.testdemo.entity.SysUserEntity;
import com.swt.testdemo.exception.AgyException;
import com.swt.testdemo.form.AddUserForm;
import com.swt.testdemo.form.EditUserForm;
import com.swt.testdemo.form.UserListForm;
import com.swt.testdemo.service.SysCommonService;
import com.swt.testdemo.service.SysRoleService;
import com.swt.testdemo.service.SysUserService;
import com.swt.testdemo.shiro.ShiroUtils;
import com.swt.testdemo.util.RedisUtil;
import com.swt.testdemo.util.ValidatorUtil;
import com.swt.testdemo.vo.AddUserVO;
import com.swt.testdemo.vo.SysUserMapVO;
import com.swt.testdemo.vo.SysUserVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author BleethNie
 * @version 1.0
 * @date 2020/11/11 11:16
 **/
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserDao, SysUserEntity> implements SysUserService {
    public static final String RANDOM_STR = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";

    private static final String DEFAULT_PASSWD = "123456";

    @Autowired
    private SysRoleService sysRoleService;

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private SysUserDao sysUserDao;


    @Autowired
    private SysCommonService sysCommonService;



    @Override
    public ResponseBean createUser(AddUserForm form) {
        //参数校验
        ValidatorUtil.validateEntity(form);


        DateTime current = DateUtil.date();
        SysUserEntity sysUserEntity = new SysUserEntity();
        BeanUtils.copyProperties(form,sysUserEntity);
        sysUserEntity.setCreatedTime(current);
        sysUserEntity.setUpdateTime(current);
        sysUserEntity.setLoginFailCount(0);
        sysUserEntity.setExpireYear(form.getExpireYear());
        sysUserEntity.setStatus(SysUserEntity.STATUS_INACTIVITY);


        //设置密码
        String salt = RandomUtil.randomString(RANDOM_STR, 20);
        sysUserEntity.setSalt(salt);
        sysUserEntity.setPassword(ShiroUtils.sha256(form.getPassword(),salt));

       //设置普通用户权限
        SysRoleEntity sysRoleEntity = sysRoleService.queryRoleByRoleType(SysRoleEntity.USER_TYPE);

        if (sysRoleEntity == null){
            throw new AgyException("未找到角色类型！！！");
        }

         sysUserEntity.setRoleId(sysRoleEntity.getRoleId());

        boolean success = this.save(sysUserEntity);
        ResponseBean responseBean = null;
        if (success){
            AddUserVO addUserVO = new AddUserVO();
            BeanUtils.copyProperties(sysUserEntity,addUserVO);
            responseBean = new ResponseBean(200,"添加成功",addUserVO);
        }


        return responseBean;
    }

    @Override
    public ResponseMessage editUser(EditUserForm form) {


        Integer userId = form.getUserId();

        //删除redis中信息
        String key = "user:"+ userId;
        redisUtil.del(key);

        SysUserEntity sysUserEntity = sysUserDao.queryUserById(userId);

        BeanUtils.copyProperties(form,sysUserEntity);

        //设置密码
        String salt = RandomUtil.randomString(RANDOM_STR, 20);
        String newPassword = ShiroUtils.sha256(form.getPassword(), salt);
        sysUserEntity.setSalt(salt);
        sysUserEntity.setPassword(newPassword);

        sysUserEntity.setUpdateTime(DateUtil.date());
        boolean success = this.updateById(sysUserEntity);

        ResponseMessage responseMessage = null;

        if (success){
           responseMessage = new ResponseMessage(200,"修改成功");
        }else {
            responseMessage = new ResponseMessage(500,"修改失败");
        }

        return responseMessage;
    }

    @Override
    public ResponseMessage deleteUser(Integer userId) {
        String key ="user:"+userId;

        //删除redis中信息
        redisUtil.del(key);

        //判断用户是否存在
        SysUserEntity userEntity = sysUserDao.queryUserById(userId);
        if (userEntity == null || SysUserEntity.STATUS_DELETE.equals(userEntity.getStatus())){
           throw new AgyException("当前用户不存在，请检查后重试.....");
        }
        userEntity.setUpdateTime(DateUtil.date());
        userEntity.setStatus(SysUserEntity.STATUS_DELETE);

        int row = sysUserDao.updateById(userEntity);
        ResponseMessage responseMessage = null;
        if (row ==1){
            responseMessage= new ResponseMessage(200,"删除成功");
        }else {
            responseMessage= new ResponseMessage(500,"删除失败");
        }

        return responseMessage;
    }

    @Override
    public ResponseMessage enableUser(Integer userId) {
       //判断用户是否存在
        SysUserEntity sysUserEntity = sysUserDao.queryUserById(userId);
        if (sysUserEntity ==null || SysUserEntity.STATUS_DELETE.equals(sysUserEntity.getStatus())){
            throw new AgyException("当前用户不存在，请检查后重试...");
        }

       //判断用户是否属于启用状态
        String status = sysUserEntity.getStatus();
        if (StrUtil.isEmpty(status) || status.equals(SysUserEntity.STATUS_ENABLE)){
             throw new AgyException("当前用户已经处于启用状态...");
        }
        if (status.equals(SysUserEntity.STATUS_DELETE)){
             throw new AgyException("当前用户不存在...");
        }
        if (status.equals(SysUserEntity.STATUS_EXPIRE)){
            throw new AgyException("当前用户已经处于过期状态，请配置授权时间...");
        }
        if (status.equals(SysUserEntity.STATUS_INACTIVITY)){
            throw new AgyException("当前用户处于未激活状态，需要用户激活后可以操作....");
        }

        sysUserEntity.setUpdateTime(DateUtil.date());
        sysUserEntity.setStatus(SysUserEntity.STATUS_ENABLE);

        int row = sysUserDao.updateById(sysUserEntity);
        if (row ==1){
            return new ResponseMessage(200,"启用成功");
        }else {
            return new ResponseMessage(500,"启用失败");
        }

    }

    @Override
    public ResponseMessage disableUser(Integer userId) {
        //判断用户是否存在
        SysUserEntity sysUserEntity = sysUserDao.queryUserById(userId);
        if (sysUserEntity ==null || SysUserEntity.STATUS_DELETE.equals(sysUserEntity.getStatus())){
            throw new AgyException("当前用户不存在，请检查后重试....");
        }

        //判断用户是否属于禁用状态
        String status = sysUserEntity.getStatus();
        if (status.equals(SysUserEntity.STATUS_DISABLE)){
            throw new AgyException("当前用户已经处于禁用状态...");
        }
        if (status.equals(SysUserEntity.STATUS_DELETE)){
            throw new AgyException("当前用户不存在");
        }
        if (status.equals(SysUserEntity.STATUS_INACTIVITY)){
            throw new AgyException("当前用户处于未激活状态....");
        }
        if (status.equals(SysUserEntity.STATUS_EXPIRE)){
            throw new AgyException("当前用户处于过期状态");
        }
        sysUserEntity.setUpdateTime(DateUtil.date());
        sysUserEntity.setStatus(SysUserEntity.STATUS_DISABLE);
        int row = sysUserDao.updateById(sysUserEntity);
        if (row ==1){
            return new ResponseMessage(200,"禁用成功");
        }else {
            return new ResponseMessage(500,"禁用异常");
        }

    }

    @Override
    public ResponseMessage resetUserPassword(Integer userId) {
        String md5= SecureUtil.md5(DEFAULT_PASSWD);
        String password = SecureUtil.md5(md5);
        String salt = RandomUtil.randomString(RANDOM_STR, 20);
        String newPassword =ShiroUtils.sha256(password,salt);


        SysUserEntity sysUserEntity = sysUserDao.queryUserById(userId);
        if (sysUserEntity ==null || sysUserEntity.getStatus().equals(SysUserEntity.STATUS_DELETE)){
            throw new AgyException("当前用户不存在，请检查后重试...");
        }
        sysUserEntity.setSalt(salt);
        sysUserEntity.setUpdateTime(DateUtil.date());
        sysUserEntity.setPassword(newPassword);
        int row = sysUserDao.updateById(sysUserEntity);
        if (row == 1){
           return new ResponseMessage(200,"密码重置成功");
        }else {
            return new ResponseMessage(500,"密码重置失败");
        }

    }

    @Override
    public ResponseBean listUser(UserListForm form) {
        //参数校验
        ValidatorUtil.validateEntity(form);


        Integer page = form.getPage();
        Integer limit = form.getLimit();
        String userFilter = form.getUserFilter();
        String areaFilter = form.getAreaFilter();
        String statusFilter = form.getStatusFilter();

        Page<SysUserVO> entityPage = new Page<>(page, limit);
        IPage<SysUserVO> resultPage = sysUserDao.listUser(entityPage, userFilter, areaFilter, statusFilter);


        List<SysRoleEntity> roleList = sysRoleService.list();

        Map<Integer, String> roleMap = CollUtil.fieldValueAsMap(roleList, "roleId", "roleType");


        List<SysUserVO> records = resultPage.getRecords();

        records= records.stream().map(vo -> {
            Integer roleId = vo.getRoleId();
            vo.setRoleType(roleMap.get(roleId));

            String areaId = vo.getAreaId();
            String areaAddress = sysCommonService.getAddress(areaId);
            vo.setAreaAddress(areaAddress);

            String areaPermission = vo.getAreaPermission();
            String areaAddressPermission = sysCommonService.getAddress(areaPermission);
            vo.setAreaPermissionAddress(areaAddressPermission);
            return vo;
        }).collect(Collectors.toList());

        return new ResponseBean(200,"查询成功",resultPage);
    }

    @Override
    public ResponseBean listUserAsMap(String userFilter, String statusFilter) {
        List<SysUserMapVO> sysUserMapVOS = sysUserDao.queryUserAsMap(userFilter, statusFilter);
        return new ResponseBean(200,"查询成功",sysUserMapVOS);
    }
}
